from django.shortcuts import render, redirect
from app02 import models
from app02.utils.pagination import Pagination

from app02.utils.form import UserModelForm


def user_list(request):
    """ 部门列表 """
    # 去数据库中获取所有的部门列表
    queryset = models.userinfo.objects.all()

    # for obj in queryset:
    # print(obj.id, obj.name, obj.password, obj.age, obj.account, obj.gender, obj.create_time.strftime('%Y-%m-%d'),obj.depart_id,obj.depart.title, obj.get_gender_display())
    # print(obj.depart_id)  # 获取数据库中存储的那个字段值
    # print(obj.depart.title)  # 根据id自动去关联的表中获取哪一行数据depart对象

    page_object = Pagination(request, queryset)

    context = {
        "user_list": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html()  # 生成页码
    }

    return render(request, 'user_list.html', context)


def user_add(request):
    if request.method == "GET":
        """ 添加用户 """
        context = {
            'gender_choices': models.userinfo.gender_choices,
            'depart_list': models.department.objects.all()
        }
        return render(request, 'user_add.html', context)

    # 获取用户提交的数据
    name = request.POST.get('add_name')
    pwd = request.POST.get('add_password')
    age = request.POST.get('add_age')
    account = request.POST.get('add_account')
    time = request.POST.get('add_time')
    gender = request.POST.get('add_gender')
    depart_id = request.POST.get('add_depart')
    # 添加到数据库中
    models.userinfo.objects.create(name=name, password=pwd, age=age, account=account, create_time=time, gender=gender,
                                   depart_id=depart_id)

    # 返回到用户列表页面
    return redirect("/user/list/")



def user_model_form_add(request):
    """ 部门用户(ModelForm版本)"""
    if request.method == "GET":
        form = UserModelForm()
        return render(request, 'user_model_form_add.html', {"form": form})

    # 用户POST提交数据，数据校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        # print(form.cleaned_data)
        form.save()
        return redirect('/user/list/')
    else:
        # 校验失败(在页面上显示错误信息)
        return render(request, 'user_model_form_add.html', {"form": form})


def user_edit(request, nid):
    """ 修改用户 """
    # 根据nid,获取数据 [obj,]
    row_object = models.userinfo.objects.filter(id=nid).first()
    if request.method == "GET":
        form = UserModelForm(instance=row_object)
        return render(request, 'user_edit.html', {"form": form})

    # 保持到数据库
    # models.userinfo.objects.filter(id=nid).update()
    # return redirect("/user/list/")
    # 用户POST提交数据，数据校验
    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/user/list/')
    else:
        # 校验失败(在页面上显示错误信息)
        return render(request, 'user_edit.html', {"form": form})


def user_delete(request, nid):
    """ 删除用户"""
    models.userinfo.objects.filter(id=nid).delete()
    return redirect("/user/list/")
